<template>
  <md-page title="举报" isBtn :btnTextItems="data.btnTextItems" @btnClick="bottomBtnClick">
    <div class="container">
      <uni-forms ref="form" :modelValue="data.formData" label-position="top" label-width="100">
        <!-- 图片上传 -->
        <uni-forms-item label="举报图片" name="images" required :rules="[{ required: true, errorMessage: '请上传举报图片' }]">
          <view class="upload-section">
            <uni-file-picker 
              v-model="data.formData.images"
              limit="3" 
              title="最多选择3张图片" 
              file-mediatype="image" 
              @select="handleUpload"
              @delete="handleDelete"
            />
            <view class="upload-tip">请上传相关图片作为举报证据</view>
          </view>
        </uni-forms-item>

        <!-- 一句话描述 -->
        <uni-forms-item label="举报描述" name="description" required :rules="[{ required: true, errorMessage: '请填写举报描述' }]">
          <uni-easyinput 
            type="textarea" 
            v-model="data.formData.description" 
            placeholder="请简要描述举报内容，如：该选手在比赛过程中作弊"
            :maxlength="200"
            :showWordLimit="true"
          />
        </uni-forms-item>

        <!-- 被举报人号码布编号 -->
        <uni-forms-item label="被举报人号码布编号" name="number" required :rules="[{ required: true, errorMessage: '请输入被举报人号码布编号' }]">
          <uni-easyinput 
            v-model="data.formData.number" 
            placeholder="请输入被举报人的号码布编号"
            type="number"
            :maxlength="20"
          />
        </uni-forms-item>

        <!-- 举报类型 -->
        <uni-forms-item label="举报类型" name="type" required :rules="[{ required: true, errorMessage: '请选择举报类型' }]">
          <uni-data-select 
            v-model="data.formData.type"
            :localdata="data.reportTypes"
            placeholder="请选择举报类型"
          />
        </uni-forms-item>

        <!-- 联系方式（可选） -->
        <uni-forms-item label="联系方式" name="contact">
          <uni-easyinput 
            v-model="data.formData.contact" 
            placeholder="请输入您的联系方式（选填）"
            type="text"
            :maxlength="50"
          />
        </uni-forms-item>
      </uni-forms>
    </div>
  </md-page>
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { uploadImage } from '@/api';
import { Toast } from '@/utils/util';
import type { BtnTextItem } from '@/components/md-ui/components/md-page/md-page.vue';

const data = reactive<any>({
  btnTextItems: [],
  formData: {
    images: [],
    description: '',
    number: '',
    type: '',
    contact: ''
  },
  reportTypes: [
    { value: 'cheating', text: '作弊行为' },
    { value: 'violence', text: '暴力行为' },
    { value: 'inappropriate', text: '不当言论' },
    { value: 'rule_violation', text: '违反规则' },
    { value: 'other', text: '其他' }
  ]
});

/**
 * 上传相关
 */
const handleUpload = async (e: any) => {
  console.log('选择文件：', e);
  let { tempFilePaths } = e;
  
  if (!tempFilePaths || tempFilePaths.length === 0) return;
  
  uni.showLoading({
    title: '图片上传中...',
    mask: true,
  });
  
  try {
    let uploadTasks = tempFilePaths.map(async (filePath: string) => {
      let res = await uploadImage({ filePath, formData: { category: 'report' } });
      const url = res.data.url;
      const name = url?.split?.('/')?.slice(-1);
      // 格式化组件需要的格式
      return {
        url,
        extname: 'png',
        name,
      };
    });
    
    const uploadedImages = await Promise.all(uploadTasks);
    data.formData.images = [...data.formData.images, ...uploadedImages];
    
    uni.hideLoading();
    console.log('所有图片上传成功', uploadedImages);
  } catch (error) {
    uni.hideLoading();
    Toast('图片上传失败，请重试');
    console.error('图片上传失败:', error);
  }
};

const handleDelete = (e: any) => {
  console.log('删除文件：', e);
  data.formData.images = data.formData.images.filter((item: any, index: number) => index !== e.index);
};

/**
 * 表单验证
 */
const validateForm = () => {
  if (!data.formData.images || data.formData.images.length === 0) {
    Toast('请上传举报图片');
    return false;
  }
  
  if (!data.formData.description.trim()) {
    Toast('请填写举报描述');
    return false;
  }
  
  if (!data.formData.number.trim()) {
    Toast('请输入被举报人号码布编号');
    return false;
  }
  
  if (!data.formData.type) {
    Toast('请选择举报类型');
    return false;
  }
  
  return true;
};

/**
 * 提交举报
 */
const submitReport = async () => {
  if (!validateForm()) return;
  
  try {
    uni.showLoading({
      title: '提交中...',
      mask: true,
    });
    
    // TODO: 调用举报API
    // const submitData = {
    //   images: data.formData.images.map((img: any) => img.url),
    //   description: data.formData.description,
    //   number: data.formData.number,
    //   type: data.formData.type,
    //   contact: data.formData.contact
    // };
    // await submitReportAPI(submitData);
    
    // 模拟提交成功
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    uni.hideLoading();
    Toast('举报提交成功，我们会尽快处理');
    
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
    
  } catch (error) {
    uni.hideLoading();
    Toast('提交失败，请重试');
    console.error('提交举报失败:', error);
  }
};

/**
 * 底部按钮点击事件
 */
const bottomBtnClick = async (info: { item: BtnTextItem }) => {
  const { key } = info.item;
  
  if (key === 'submit') {
    uni.showModal({
      title: '确认提交',
      content: '确认提交举报信息吗？提交后将无法修改。',
      success: res => {
        if (res.confirm) {
          submitReport();
        }
      },
    });
  }
};

onLoad(() => {
  // 设置底部按钮
  data.btnTextItems = [
    {
      text: '提交举报',
      key: 'submit',
      color: '#d92121',
      textColor: '#ffffff',
    }
  ];
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  min-height: calc(100vh - 200rpx);
  
  .upload-section {
    .upload-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
      line-height: 1.4;
    }
  }
  
  :deep(.uni-forms-item) {
    margin-bottom: 40rpx;
    
    .uni-forms-item__label {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
      margin-bottom: 20rpx;
    }
    
    .uni-easyinput__content {
      border-radius: 10rpx;
      border: 2rpx solid #e5e5e5;
      
      .uni-easyinput__content-input {
        font-size: 28rpx;
        color: #333;
      }
    }
    
    .uni-data-select {
      .uni-stat__select {
        border-radius: 10rpx;
        border: 2rpx solid #e5e5e5;
        font-size: 28rpx;
      }
    }
  }
  
  :deep(.uni-file-picker) {
    .uni-file-picker__container {
      border-radius: 10rpx;
      border: 2rpx dashed #e5e5e5;
      
      .uni-file-picker__input-box {
        background-color: #f8f8f8;
      }
    }
  }
}
</style>
